﻿using ExportExcelDemo.Core;
using ExportExcelDemo.Core.Helper;
using ExportExcelDemo.Core.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;



namespace ExportExcelDemo.Web.Controllers
{
    public class HomeController : Controller
    {
        private const string prefix_stu = "stu";
        private const string prefix_tea = "tea";
        public readonly string[] _fileTypes = { prefix_stu, prefix_tea };
        public ActionResult Index()
        {

            SchoolManager schoolManager = new SchoolManager();
            string schoolNum = schoolManager.GetSchoolNum("廊坊师范学院");
            ViewBag.SchoolNum = schoolNum;
            return View();
        }

        [HttpPost()]
        public JsonResult ImportData()
        {
            try
            {
                //文件类型，学校编号
                Tuple<string, string, HttpPostedFileBase> tuble = ValidateFile();
                var file = tuble.Item3;
                var server = HttpContext.Server;
                string tempFileDownloadFolder = server.MapPath("~/Temp/Downloads");
                AppFileHelper.DeleteFilesInFolderIfExists(tempFileDownloadFolder, file.FileName);
                //保存到临时文件夹
                var tempFilePath = Path.Combine(tempFileDownloadFolder, file.FileName);
                file.SaveAs(tempFilePath);
                string r = string.Empty;
                r = ImportDataInteral(tempFilePath, tuble.Item1, tuble.Item2);
               
                return Json(r);

            }
            catch (Exception ex)
            {
                return Json(ex.Message);
            }
        }

        /// <summary>
        /// 验证文件是否合规
        /// </summary>
        /// <returns></returns>

        public Tuple<string, string, HttpPostedFileBase> ValidateFile()
        {
            if (Request.Files.Count <= 0 || Request.Files[0] == null)
            {
                throw new Exception("未找到文件");
            }
            var file = Request.Files[0];
            if (file.ContentLength > 1024 * 1024 * 5) //5m
            {
                throw new Exception("文件不能超过5M");
            }
            string[] names = System.IO.Path.GetFileNameWithoutExtension(file.FileName).Split('_');//下划线分隔
            string msg = "文件名称错误,请根据导入提示来修改文件名称";
            if (names.Length != 2)
            {
                throw new Exception(msg);
            }
            if (!_fileTypes.Contains(names[0].ToLower()))
            {
                throw new Exception(msg);
            }
            if (string.IsNullOrWhiteSpace(names[1]))
            {
                throw new Exception(msg);
            }
            SchoolManager schoolManager = new SchoolManager();
            string schoolNum = schoolManager.GetSchoolNum(names[1]);
            if (string.IsNullOrEmpty(schoolNum))
            {
                throw new Exception("传入的学校名不存在");
            }
            return new Tuple<string, string, HttpPostedFileBase>(names[0], names[1],file);

        }

        private string ImportDataInteral(string filePath,string fileDateType,string schoolNum)
        {
            DataSet ds = ExeclHelper.ToDataTable(filePath);//根据文件路径转换为
            DataTable dt = ds.Tables[0];

            int rowsCount = dt.Rows.Count;
            int totalRows = rowsCount;

            StringBuilder successMessage = new StringBuilder();
            StringBuilder errMessage = new StringBuilder();

            Action<DataRow, string> action;
            switch (fileDateType)
            {
                case prefix_stu:
                    action = RowDataProcessForStu;break;
                case prefix_tea:
                    action = RowDataProcessForTea;break;
                default:
                   return  errMessage.Append($"文件名前缀{fileDateType}错误").ToString();
            }
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                DataRow dr = dt.Rows[i];
                try
                {
                    action(dr, schoolNum);
                    successMessage.Append($"第{i + 1}行:导入成功\r\n");
                }
                catch (System.Exception ex)
                {
                    var error = $"第{i + 1}行 :{ex.Message}\r\n";
                    errMessage.Append(error);
                    continue;
                }
            }
            return errMessage.ToString() + successMessage.ToString();

        }

        private void RowDataProcessForStu(DataRow dr,string schoolNum)
        {
            Student model = new Student();
            model.Name = dr[0].ToString();
            model.Grade =Convert.ToInt32(dr[1]);
            model.Age=Convert.ToInt32(dr[2]);
            model.SchoolNum = schoolNum;
            StudentManager studentManager = new StudentManager();
            studentManager.InsertStudent(model);

        }

        private void RowDataProcessForTea(DataRow dr, string schoolNum)
        {
            Teacher model = new Teacher();
            model.Name = dr[0].ToString();
            model.Age = Convert.ToInt32(dr[1]);
            model.SchoolNum = schoolNum;
            TeacherManager teacherManager = new TeacherManager();
            teacherManager.InsertTeacher(model);
        }


    }
}